#!/bin/bash
#Author: YangYi
#Date: 2025-03-28
#Version: v1
#Content 一键诊断、处置原子能力，node组件检测列表
#1.kube-proxy
#2.kubelet
#3.docker/crictl
#4.证书有效期



# ---------------------------初始化全局变量----------------------------

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m' # 恢复默认颜色

# 组件列表
COMPONENTS=("docker" "kube-proxy" "kubelet" "flanneld")

# 证书文件列表
CERT_FILES=(
    "/etc/kubernetes/ssl/kube-proxy.pem"
    "/etc/kubernetes/ssl/kubelet-client.crt"
)


# ----------------------------功能模块函数-----------------------------

# 检查组件状态函数
check_component() {
    component=$1
    status=$(systemctl is-active $component 2>/dev/null)
    
    if [ "$status" == "active" ]; then
        echo -e "${GREEN}[OK] ${component} 服务正在运行${NC}"
    else
        echo -e "${RED}[FAIL] ${component} 服务未运行！${NC}"
        echo "尝试启动服务..."
        sudo systemctl start $component
        new_status=$(systemctl is-active $component)
        if [ "$new_status" == "active" ]; then
            echo -e "${YELLOW}[WARNING] 服务已尝试重启，请检查日志${NC}"
        else
            echo -e "${RED}[CRITICAL] 服务启动失败！${NC}"
            exit 1
        fi
    fi
}

# 检查证书有效期函数
check_cert_expiry() {
    cert_path=$1
    expiry_date=$(openssl x509 -in $cert_path -noout -dates | awk -F= '/notAfter/{print $2}')
    
    if [ -z "$expiry_date" ]; then
        echo -e "${RED}[ERROR] 证书文件不存在: $cert_path${NC}"
        return
    fi

    current_date=$(date +%s)
    expiry_timestamp=$(date -d "$expiry_date" +%s 2>/dev/null)
    
    if [ -z "$expiry_timestamp" ]; then
        echo -e "${YELLOW}[WARNING] 无法解析证书过期时间: $cert_path${NC}"
        return
    fi

    days_remaining=$(( (expiry_timestamp - current_date) / 86400 ))
    
    if [ $days_remaining -lt 30 ]; then
        echo -e "${RED}[警告] 证书即将过期: $cert_path (剩余 $days_remaining 天)${NC}"
    elif [ $days_remaining -lt 90 ]; then
        echo -e "${YELLOW}[注意] 证书将在 $days_remaining 天后过期: $cert_path${NC}"
    else
        echo -e "${GREEN}[OK] 证书有效期充足: $cert_path (剩余 $days_remaining 天)${NC}"
    fi
}

# 主检查流程
echo -e "${YELLOW}===== 开始检查Kubernetes Node组件状态 =====${NC}"

for component in "${COMPONENTS[@]}"; do
    check_component $component
done

echo -e "\n${YELLOW}===== 开始检查证书有效期 =====${NC}"

for cert in "${CERT_FILES[@]}"; do
    check_cert_expiry $cert
done

echo -e "\n${YELLOW}===== 检查完成 =====${NC}"
